package com.thinkTank.oa.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.thinkTank.oa.entity.Dictiontry;
import com.thinkTank.oa.service.DictiontryService;

public class SystemGlobals {
	//缓存数据字典
	private Map<String,List<Dictiontry>> dictiontryMap = new HashMap<String,List<Dictiontry>>();
	
	 private ApplicationContext app;  
	
	 private SystemGlobals(){
		 
	}
	 
	private static SystemGlobals globals = new SystemGlobals();
	
	
	public static SystemGlobals getInstance() {
		return globals;
	}
	
	/***
	 * 初始化全局变量
	 * @param context servlet 上下文
	 */
	public  void initializing(ServletContext context){
		
		   app = (ApplicationContext) WebApplicationContextUtils.getWebApplicationContext(context);
		   /***
		    * 读取数据库数据字典并赋值给map
		    */
		   DictiontryService dictiontryService =(DictiontryService)app.getBean("dictiontryService");
		   List<Dictiontry> dicList = dictiontryService.queryAll(new Dictiontry());
		   if(dicList != null && dicList.size()>0){
			   for(Dictiontry dic :dicList){
				   String dicGroup = dic.getGroupName();
				   if(dictiontryMap.containsKey(dicGroup)){
					   dictiontryMap.get(dicGroup).add(dic);
				   }else{
					   List<Dictiontry> newDic = new  ArrayList<Dictiontry>();
					   newDic.add(dic);
					   dictiontryMap.put(dicGroup, newDic );
				   }
			   }
			   	List<Dictiontry> country =dictiontryMap.get(Constant.DICTIONTRY_COUNTRY);
			   	Collections.sort(country,new Comparator<Dictiontry>(){
			    	public int compare(Dictiontry p1, Dictiontry p2) {
		                if( p1.getWorth().compareTo(p2.getWorth())<0){
		                    return -1;
		                   
		                }
		                
		                return 1;
		            }
			    });
		   }
	}

	public Map<String, List<Dictiontry>> getDictiontryMap() {
		return dictiontryMap;
	}
	public List<Dictiontry> getDictiontryMap(String key) {
		return dictiontryMap.get(key);
	}
	public void setDictiontryMap(Map<String, List<Dictiontry>> dictiontryMap) {
		this.dictiontryMap = dictiontryMap;
	}
	
}
